﻿using System;
using System.Linq.Expressions;

namespace Manoso.Data.FluentMap.Converter
{
    internal static class SqlConverter
    {
        public static string ToSql(this LambdaExpression lambda, IMapAdaptor adaptor, params string[] alias)
        {
            if (lambda == null) return null;

            var parameters = lambda.Parameters;
            if (parameters.Count <= 0) return null;

            var visitor = new MapVisitor(adaptor);
            visitor.Visit(lambda);

            var literal = visitor.Literal;
            literal.Replace("AndAlso", "And")
                .Replace("OrElse", "Or");

            var count = Math.Min(parameters.Count, alias.Length);
            for (var i = 0; i < count; i++)
            {
                literal = literal.Replace(parameters[i].Name, alias[i]);
            }

            return literal.ToString();
        }
    }
}
